import React, { useMemo } from 'react';
import { render as renderAmis, ToastComponent, AlertComponent } from 'amis';
import { alert, confirm } from 'amis';
import { request } from '@umijs/max';
import type { SchemaNode } from 'amis/lib/types';
import 'amis/lib/themes/antd.css';
import 'amis/lib/helper.css';
import 'amis/sdk/iconfont.css';

export interface AmisRendererProps {
  schema: SchemaNode;
  data?: Record<string, any>;
}

interface ApiResponse<T = any> {
  data?: T;
  list?: T[];
  total?: number;
}

const AmisRenderer: React.FC<AmisRendererProps> = ({ schema, data = {} }) => {
  // 使用 useMemo 缓存环境配置，避免重复创建
  const env = useMemo(() => ({
    alert,
    confirm,
    fetcher: async ({
      url,
      method = 'get',
      data,
      config = {},
      headers = {}
    }: {
      url: string;
      method?: string;
      data?: any;
      config?: Record<string, any>;
      headers?: Record<string, any>;
    }) => {
      try {
        // 构建请求配置
        const requestConfig = {
          ...config,
          method,
          headers: {
            'Content-Type': 'application/json',
            ...headers
          },
          ...(method.toLowerCase() !== 'get' && data && typeof data !== 'string'
            ? { data }
            : data
            ? { params: data }
            : {})
        };

        const response = await request<ApiResponse>(url, requestConfig);

        if (!response) {
          throw new Error('接口返回数据格式不正确');
        }

        // 统一处理响应数据
        const processResponse = (res: ApiResponse) => {
          const items = Array.isArray(res)
            ? res
            : res.data?.list || res.list || res.data || res;
          const total = res.total || (Array.isArray(items) ? items.length : 0);

          return {
            status: 0,
            msg: '',
            data: { items, total }
          };
        };

        return processResponse(response);
      } catch (error: any) {
        console.error('API Error:', error);
        return {
          status: error.status || 500,
          msg: error.message || '接口请求失败',
          data: error.response?.data || null
        };
      }
    },
    isCancel: (value: any) => {
      return !!(value && (value.type === 'cancel' || value.name === 'CanceledError'));
    },
    copy: async (contents: string) => {
      try {
        await navigator.clipboard?.writeText?.(contents);
        alert('内容已复制到剪贴板');
      } catch (err) {
        console.error('复制失败:', err);
        alert('复制失败，请手动复制');
      }
    },
    jumpTo: (location: string) => {
      window.location.href = location;
    }
  }), []); // 空依赖数组，因为这些配置不依赖于任何 props 或 state

  return (
    <div className="amis-scope">
      <ToastComponent key="toast" />
      <AlertComponent key="alert" />
      {renderAmis(
        schema,
        {
          data,
          theme: 'antd',
          locale: 'zh-CN'
        },
        env
      )}
    </div>
  );
};

export default AmisRenderer;